

package com.bei_en.teacher.admin.controller.order;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bei_en.teacher.admin.model.order.bean.OrderBasic;
import com.bei_en.teacher.admin.model.order.condition.OrderBasicCondition;
import com.bei_en.teacher.admin.model.order.vo.OrderBasicVo;
import com.bei_en.teacher.admin.model.questions.vo.QuestionsVo;
import com.bei_en.teacher.admin.service.order.OrderBasicService;
import com.bei_en.teacher.admin.controller.BaseController;
import com.bei_en.teacher.third.pay.controller.AlipayController;
import com.bei_en.teacher.third.pay.controller.LinWeixinController;
import com.bei_en.teacher.third.pay.web.Mwxpay.MD5Util;
import com.bei_en.teacher.third.pay.web.alipay.RSA;
import com.bei_en.common.util.interceptor.OAuthRequired;
import com.bei_en.common.web.JsonFailResult;
import com.bei_en.common.web.JsonResult;
import com.bei_en.common.web.JsonSuccessResult;
import com.mysql.fabric.xmlrpc.base.Array;
/**
 * （订单）
 * @author Guocg
 * @date 2016-12-22 9:44:24
 */
@Controller
@RequestMapping("/api/OrderBasic")
public class OrderBasicAPPController extends BaseController {

    @Autowired
    OrderBasicService orderBasicService;


    @RequestMapping("/orderBasic")
	@ResponseBody
    public JsonResult orderBasic(Model model,@Valid  OrderBasicCondition vo, BindingResult br, HttpSession session ) {
    	if (br.hasErrors())
       		return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
    	
     	try {
     		
     	   List<OrderBasicVo> list =new ArrayList<OrderBasicVo>();
		   list = orderBasicService.findOrderBasicPage(vo);
		   JSONArray array=new JSONArray();
		   JSONObject object=null;
		   OrderBasicVo orderBasicVo=null;
		   for (int i = 0; i < list.size(); i++) {
			   object=new JSONObject();
			   orderBasicVo=list.get(i);
	   seetingJsonObject(object,"id",  orderBasicVo.getId());
	   seetingJsonObject(object,"orderNum",  orderBasicVo.getOrderNum());
	   seetingJsonObject(object,"payTime",  orderBasicVo.getPayTime());
	   seetingJsonObject(object,"orderType",  orderBasicVo.getOrderType());
	   seetingJsonObject(object,"consultationId",  orderBasicVo.getConsultationId());
	   seetingJsonObject(object,"userId",  orderBasicVo.getUserId());
	   seetingJsonObject(object,"paymentTime",  orderBasicVo.getPaymentTime());
	   seetingJsonObject(object,"paymentGateway",  orderBasicVo.getPaymentGateway());
	   seetingJsonObject(object,"paymentNumber",  orderBasicVo.getPaymentNumber());
	   seetingJsonObject(object,"description",  orderBasicVo.getDescription());
	   seetingJsonObject(object,"orderAmount",  orderBasicVo.getOrderAmount());
	   seetingJsonObject(object,"status",  orderBasicVo.getStatus());
	   seetingJsonObject(object,"createTime",  orderBasicVo.getCreateTime());
	   seetingJsonObject(object,"updateTime",  orderBasicVo.getUpdateTime());
			   array.add(object);
		}
		return new JsonSuccessResult(session.getId(), array);
		
     	} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
    }
	 
    
    @RequestMapping("/orderBasicAdd")
    @ResponseBody
	@OAuthRequired
    public JsonResult orderBasicAdd(Model model,@Valid  OrderBasicCondition vo, BindingResult br, HttpSession session) {
      	if (br.hasErrors())
       		return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
      	try {
      		OrderBasicCondition orderBasicCondition=new OrderBasicCondition();
      		orderBasicCondition.setUserId(getUser(session).getUserId());
      		List<OrderBasicVo> orderBasicVos=		orderBasicService.findOrderBasicPage(orderBasicCondition);
      		OrderBasicVo orderBasic=new OrderBasicVo();
      		if(!orderBasicVos.isEmpty()){
      			orderBasic=orderBasicVos.get(0);
      		}else{
//      		   orderBasic.setId(vo.getId());
      			String num=new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date(System.currentTimeMillis()));
      			System.out.println(num);
      		   orderBasic.setOrderNum(num);
//      		   orderBasic.setPayTime(vo.getPayTime());
      		   orderBasic.setOrderType(vo.getOrderType());
      		   orderBasic.setConsultationId(vo.getConsultationId());
      		   orderBasic.setUserId(getUser(session).getUserId());
//      		   orderBasic.setPaymentTime(vo.getPaymentTime());
//      		   orderBasic.setPaymentGateway(vo.getPaymentGateway());
//      		   orderBasic.setPaymentNumber(vo.getPaymentNumber());
      		   orderBasic.setDescription("打赏");
      		   orderBasic.setOrderAmount(vo.getOrderAmount());
      		   orderBasic.setStatus(1);
      		   orderBasic.setCreateTime(new Date());
      		   orderBasic.setUpdateTime(new Date());
      		 orderBasic.setPayTime((int)(System.currentTimeMillis()/1000));
      		   orderBasicService.insert(orderBasic);
      		}
	   
		HashMap<String, String> map = new HashMap();
		map.put("order", orderBasic.getOrderNum());
		String url = "";
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YmdH");
		Date tempDate=new Date();
		switch(vo.getOrderType()){
		case 1:
			url = getAlipayUrl(orderBasic);
			String[] split = url.split("___");
			map.put("url", split[0]);
			map.put("sign", split[1]);
			break;
		case 2:
			HashMap<String, String> map2 = new HashMap();
			map.put("appid", "wx1f8e4056c43072be");
			map.put("mch_id", "1424464102");
			map.put("nonce_str", "65173795697c8229dd202ad94e821bab");
			map.put("body", "打赏");
			map.put("out_trade_no", orderBasic.getOrderNum()+"-"+simpleDateFormat.format(tempDate));
			map2.put("total_fee", new Double(orderBasic.getOrderAmount()*100).intValue()+"");
//			map.put("total_fee", "1");
			map.put("spbill_create_ip", request.getRemoteAddr());
			map.put("trade_type", "APP");
			map.put("notify_url", LinWeixinController.notify_url2);
			// 签名
			map2.put("appid", "wx1f8e4056c43072be");
			map2.put("mch_id", "1424464102");
			map2.put("nonce_str", "65173795697c8229dd202ad94e821bab");
			map2.put("body","打赏");
			map2.put("out_trade_no", orderBasic.getOrderNum()+"-"+simpleDateFormat.format(tempDate));
			map2.put("total_fee", new Double(orderBasic.getOrderAmount()*100).intValue()+"");
//			map2.put("total_fee", "1");
			map2.put("spbill_create_ip", request.getRemoteAddr());
			map2.put("trade_type", "APP");
			map2.put("notify_url", LinWeixinController.notify_url2);
			String sign = "";
			SortedMap<String, String> sort = new TreeMap<String, String>(
					map2);
			Set<Entry<String, String>> entry1 = sort.entrySet();
			Iterator<Entry<String, String>> it = entry1.iterator();
			while (it.hasNext()) {
				Entry<String, String> entry = it.next();
				sign += entry.getKey() + "=" + entry.getValue() + "&";
				System.out.println("排序之后:" + entry.getKey() + " 值"
						+ entry.getValue());
			}
			sign += "key=yikaoshi20161220yikaoshi14822114";
			String packageSign = MD5Util.MD5Encode(sign, "").toUpperCase();

			System.out.println(packageSign);
			map.put("sign", packageSign);
			break;
		}
		map.put("payType", orderBasic.getOrderType()+"");
	   
	   
			return new JsonSuccessResult(session.getId(), "成功",map);
      	} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
    }
    @ResponseBody
	private String getAlipayUrl(OrderBasicVo vo) {

	
		String url = "";

	
		String price="";

		price=vo.getOrderAmount()+"";
//		price="0.01";
		url = getOrderInfo(vo.getOrderNum(),"会员卡购买", "订单号"
				+ vo.getOrderNum(), price);

		String sign = RSA.sign(url, AlipayController.my_private_key, "utf-8");
		try {
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return url+ "&sign=\"" + sign + "\"&"+"sign_type=\"RSA\"" + "___" + sign;

	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String code, String subject, String body,
			String price) {
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YmdHms");
		code=code	+"-"+simpleDateFormat.format(new Date());
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + AlipayController.partner + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"2991459855@qq.com\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + code + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + AlipayController.notify_url
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"" + AlipayController.PAY_TIME1 + "m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		// orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}
    
    
    @RequestMapping("/orderBasicEdit")
    public JsonResult orderBasicEdit(Model model,@Valid  OrderBasicCondition vo, BindingResult br, HttpSession session) {
      	if (br.hasErrors())
       		return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
      	
    	try {
    	OrderBasicVo orderBasic=new OrderBasicVo();
	
		orderBasicService.updateSelective(orderBasic);
	
		return new JsonSuccessResult(session.getId(), "成功");
		
     	} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
    }

  
    
}
